<?php 
require_once(__DIR__ . '/CommonClass/errorcode.php');
require_once(__DIR__ . '/account.controller.php');

/**
 * Create or Update Account
 * NOTE: If Updating account with identical content as existing, update will FAIL.
 * @param $userName string
 * @param $passHash string
 * @param $authUser string
 * @param $authUserHash  string
 * @param $dataHash string
 * @return array
*/
function putAccount($username, $passHash, $authUsername, $authPass, $dataHash) {
	if (empty($username)){
		return array(ErrorCode::failCreate + 100);
	}
	if (empty($passHash)) {
		return array(ErrorCode::failCreate + 200);
	}
	if (empty($authUsername)) {
		return array(ErrorCode::failCreate + 300);
	}
	if (empty($authPass)) {
		return array(ErrorCode::failCreate + 400);
	}

	$controller = new AccountController();
	$exist = $controller -> requestHandler(array(
			':accName' => $username));

	if ($exist[0]== ErrorCode::successRead) {
		//update path
		if(!($controller -> authenticateValidator($authUsername, $authPass))){
			return array(ErrorCode::authFailUpdate);
		}
		if (!($controller -> managerValidator($authUsername))) {
			return array(ErrorCode::authFailUpdate);
		}

		return $controller -> updateHandler(array(
				':accName' => $username,
				':password' => $passHash,
				'dataHash' => $dataHash
		));
	} else {
		//create path
		if(!($controller -> authenticateValidator($authUsername, $authPass))){
			return array(ErrorCode::authFailCreate);
		}
		if (!($controller -> managerValidator($authUsername))) {
			return array(ErrorCode::authFailCreate);
		}

		return $controller -> createHandler(array(
				':accName' => $username,
				':password' => $passHash
		));
	}
}
?>